package leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class LeetCode40 {

    public static void main(String[] args) {
        LeetCode40 leetCode39 = new LeetCode40();
        System.out.println(leetCode39.combinationSum2(new int[]{10, 1, 2, 7, 6, 1, 5}, 8));
    }

    int[] dict;
    //List<List<Integer>> result = new ArrayList<>();

    public List<List<Integer>> combinationSum21(int[] candidates, int target) {
        dict = candidates;
        Arrays.sort(dict);
        calculation(target, -1, new ArrayList<>());
        return result;
    }

    private void calculation(int target, int minIndex, List<Integer> lastList) {
        if (target == 0) {
            result.add(lastList);
            return;
        }
        if (target < dict[0])
            return;
        for (int i = minIndex + 1; i < dict.length; i++) {
            if (dict[i] > target)
                break;
            List<Integer> list = new ArrayList<>(lastList);
            list.add(dict[i]);
            calculation(target - dict[i], i, list);
        }
    }
//------------------------------------------------------------------

    public List<List<Integer>> result = new LinkedList<>();

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        if (candidates.length == 0) {
            return result;
        }
        Arrays.sort(candidates);
        comSum2(candidates, target, 0, new LinkedList<Integer>());
        return result;

    }

    public void comSum2(int[] candidates, int target, int index, LinkedList<Integer> trace) {
        //满足结束条件
        if (target == 0) {
            result.add(new LinkedList(trace));
            return;
        }
        if (target > 0) {
            //选择列表，并加上约束
            for (int i = index; i < candidates.length; i++) {
                //如果以当前结点为头结点的所有组合都找完了，那么下一个与他他相同的头结点就不用去找了。
                if (i > index && candidates[i] == candidates[i - 1]) continue;
                //做出选择
                trace.add(candidates[i]);
                comSum2(candidates, target - candidates[i], i + 1, trace);
                //撤销选择
                trace.removeLast();
            }
        }
    }
}
